package com.luxshare.aos.demo.service;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileService {
    private Context context;

    public FileService(Context context) {
        this.context = context;
    }

    public void save(String fileName, String content, int mode) {
        try {
            FileOutputStream fos = context.openFileOutput(fileName, mode);
            fos.write(content.getBytes());
            fos.flush();
            fos.close();
        } catch (Exception e) {
            Log.e(FileService.class.getName(), e.getMessage());
        }
    }

    public void save(String fileName, String content) {
        save(fileName, content, Context.MODE_PRIVATE);
    }

    public void saveToSDCard(String fileName, String content) {
        try {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File file = new File(Environment.getExternalStorageDirectory(), fileName);
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(content.getBytes());
                fos.flush();
                fos.close();
            } else {
                Log.e(FileService.class.getName(), "未检测到SD卡");
            }
        } catch (Exception e) {
            Log.e(FileService.class.getName(), e.getMessage());
        }
    }

    public String readFile(String fileName) {
        String result = null;
        FileInputStream fis = null;
        ByteArrayOutputStream os = null;
        try {
            fis = context.openFileInput(fileName);
            os = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            while (fis.read(buff) > 0) {
                os.write(buff);
            }
            byte[] totalBuff = os.toByteArray();
            result = new String(totalBuff);
        } catch (Exception e) {
            Log.e(FileService.class.getName(), e.getMessage());
        } finally {
            try {
                if (fis != null)
                    fis.close();
                if (os != null)
                    os.close();
            } catch (Exception e) {
            }
        }
        return result;
    }

}
